/*
 * MIT License
 * 
 * Copyright (c) 2017 wen.gu <454727014@qq.com>
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

/*****************************************************************************
 * Name:tiny_event_router.c
 *
 * Purpose: event router implementation
 *     
 * Version: 0.1
 *
 * Developer:
 *     wen.gu,2017-03-09
 *
 *
 *****************************************************************************/
#include <string.h>
#include <stdio.h>

#include "general_macro.h"

#include "vos_mem.h"
#include "vos_mutex.h"
#include "vos_condition.h"

#include "tiny_event_router_internal.h"
#include "tiny_event_looper_internal.h"
#include "tiny_event_router.h"


/***************************************************************************
 *
 * macro declaration
 *
 ***************************************************************************/
#define LOGE printf
#define LOGD printf
#define LOGW printf
/***************************************************************************
 *
 * data structure declaration
 *
 ***************************************************************************/


/***************************************************************************
 *
 * inner API define 
 *
 ***************************************************************************/

static my_looper_t* terFindLooper(my_event_router_t* mer, tiny_list_node_t** prev, tiny_looper_id id)
{
	my_looper_t* ml = NULL;
	tiny_list_node_t* node = tfListFront(&(mer->loopers));
	tiny_list_node_t* prev_node = node;

	while (node)
	{
		my_looper_t* temp = (my_looper_t*)node;
		if (temp->id == id)
		{
			ml = temp;
			break;
		}

		prev_node = node;
		node = node->next;
	}

	*prev = prev_node;

	return ml;
}

static inline my_reply_t* terFindReply(my_event_router_t* mer, tiny_list_node_t** prev,  GU32 reply_id)
{
	my_reply_t* mr = NULL;
	tiny_list_node_t* node = tfListFront(&(mer->replies));
	tiny_list_node_t* prev_node = node;

	while (node)
	{
		my_reply_t* temp = (my_reply_t*)node;
		if (temp->reply_id == reply_id)
		{
			mr = temp;
			break;
		}

		prev_node = node;
		node = node->next;
	}

	*prev = prev_node;

	return mr;
}

static inline my_reply_t* terReplyCreate(tiny_event_t* evt, GU32 reply_id)
{
	my_reply_t* mr = (my_reply_t*)memAlloc(sizeof(my_reply_t));
	GCHECK(mr);
	mr->evt = evt;
	mr->reply_id = reply_id;

	return mr;
}

static GS32 terPost_l(my_event_router_t* mer, tiny_event_t* evt)
{
	GS32 ret = G_ErrorBadParameter;

	my_looper_t* ml = NULL;
	tiny_list_node_t* prev = NULL;

	ml = terFindLooper(mer,&prev, evt->target);

	if (ml)
	{
		telPost(ml, evt);
	}
	else
	{
		LOGE("target looper(id:0x%08x) not found\n", evt->target);
	}

	return ret;
}

GS32 terPost(my_event_router_t* mer, tiny_event_t* evt)
{
	GS32 ret = G_ErrorBadParameter;

	vosMutexLock(mer->lock);
	ret = terPost_l(mer, evt);
	vosMutexUnlock(mer->lock);

	return ret;	
}

void terReply(my_event_router_t* mer, tiny_event_t* evt, GU32 reply_id)
{
	my_reply_t* mr = NULL;
	tiny_list_node_t* prev = NULL;
	vosMutexLock(mer->lock);
	mr = terFindReply(mer, &prev, reply_id);
	GCHECK(mr == NULL); /**cann't have same reply id, in replise queue */
	mr = terReplyCreate(evt, reply_id);

	tfListPushBack(&(mer->replies), (tiny_list_node_t*)mr);
	vosCondBroadcast(mer->replies_condition);

	vosMutexUnlock(mer->lock);
}

GS32 terPostAndWaitResponse(my_event_router_t* mer, tiny_event_t* evt, tiny_event_t** response)
{
	GS32 ret = G_ErrorBadParameter;
	GU32 reply_id = 0;
	my_reply_t* mr = NULL;
	tiny_list_node_t* prev = NULL;

	vosMutexLock(mer->lock);

	reply_id = mer->next_reply_id++;
	evt->reply_id = reply_id;
	ret = terPost_l(mer, evt);

	while (((mr = terFindReply(mer, &prev, reply_id)) == NULL) && (mer->is_alive == GTRUE))
	{
		vosCondWait(mer->replies_condition, mer->lock);
	}

	if (mr)
	{
		*response = mr->evt;

		tfListRemoveFast(&(mer->replies), prev, (tiny_list_node_t*)mr);
		ret = G_OK;
	}
	else
	{
		ret = G_ErrorEOF;
	}
	vosMutexUnlock(mer->lock);

	return ret;
}

 void terUnregisterLooper(my_event_router_t* mer, tiny_looper_id looper_id)
 {
	 my_looper_t* ml = NULL;
	 tiny_list_node_t* prev = NULL;
	vosMutexLock(mer->lock);
	 
	ml = terFindLooper(mer, &prev, looper_id);

	if (ml)
	{
		ml->id = TINY_INVALID_LOOPER_ID;
		ml->router = NULL;
		tfListRemoveFast(&(mer->loopers), prev, (tiny_list_node_t*)ml);
	}

	vosMutexUnlock(mer->lock);
 }
/***************************************************************************
 *
 * API define 
 *
 ***************************************************************************/

GPHD tfRouterCreate(void)
{
	my_event_router_t* mer = (my_event_router_t*)memAlloc(sizeof(my_event_router_t));

	if (mer)
	{
		memset(mer, 0, sizeof(*mer));

		mer->lock = vosMutexCreate();

		GCHECK(mer->lock);

		mer->replies_condition = vosCondCreate();
		GCHECK(mer->replies_condition);

		tfListInitialize(&(mer->loopers), NULL);
		tfListInitialize(&(mer->replies), memFree);
		mer->next_looper_id = 1;
		mer->next_reply_id = 1;
		mer->is_alive = GTRUE;
	}
	else
	{
		LOGE("alloc router instance failed\n");
	}

	return mer;
}

void tfRouterDestroy(GPHD router)
{
	if (router)
	{
		my_event_router_t* mer = (my_event_router_t*)router;
		GU32 looper_cnt = tfListCount(&(mer->loopers));

		if (looper_cnt > 0)
		{
			LOGW("have %d looper in router, it must release before destroy router\n", looper_cnt);
		}		
		
		vosMutexLock(mer->lock);		
		mer->is_alive = GFALSE;
		vosCondBroadcast(mer->replies_condition);
		tfListClear(&(mer->loopers));
		tfListClear(&(mer->replies));
		vosMutexUnlock(mer->lock);

		if (mer->lock)
		{
			vosMutexFree(mer->lock);
		}

		if (mer->replies_condition)
		{
			vosCondFree(mer->replies_condition);
		}



		memFree(router);
	}
}


tiny_looper_id tfRouterRegisterLooper(GPHD router, GPHD looper)
{
	tiny_looper_id ret = TINY_INVALID_LOOPER_ID;
	if (router && looper)
	{
		my_event_router_t* mer = (my_event_router_t*)router;
		my_looper_t* ml = (my_looper_t*)looper;

		vosMutexLock(mer->lock);
		
		if (ml->id == TINY_INVALID_LOOPER_ID)
		{
			ml->id = mer->next_looper_id++;
			ml->router = router;
			tfListPushBack(&(mer->loopers), (tiny_list_node_t*)looper);

			ret = ml->id;
		}
		else
		{
			LOGW("this looper already registered, the id is: %d\n", ml->id);
		}
		
		vosMutexUnlock(mer->lock);
	}

	return ret;
}
